package geekstudy.week9;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 22. 括号生成
 * https://leetcode-cn.com/problems/generate-parentheses/
 *
 * 执行结果：  通过  显示详情
 *
 * 添加备注
 * 执行用时：0 ms, 在所有 Java 提交中击败了100.00% 的用户
 * 内存消耗：38.6 MB, 在所有 Java 提交中击败了49.95% 的用户
 *
 *
 */
public class Week9GenerateParentheses {


    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        backtrack(list, new StringBuilder(),0, 0, n);
        return list;
    }

    public void backtrack(List<String> list, StringBuilder builder, int open, int close, int max) {
        if(builder.length() == max * 2) {
            list.add(builder.toString());
            return;
        }
        if(open < max) {
            builder.append('(');
            backtrack(list, builder, open + 1, close, max);
            builder.deleteCharAt(builder.length() - 1);
        }
        if(close < open) {
            builder.append(')');
            backtrack(list, builder, open, close + 1, max);
            builder.deleteCharAt(builder.length() - 1);
        }
    }
}
